package cn.com.callback;

import cn.com.elite.EliteBean;
import cn.com.kh.KHDBConfig;
import cn.com.kh.KHSWUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @projectName: ngsapitask-sw
 * @className: autoUnicomSMSResult
 * @author: LiJT
 * @description: 联通短信平台发送成功回调异常时通过这个自动任务再次获取发送结果
 * @date: 2022-09-27 00:12
 * @version: 1.0
 */

public class autoUnicomResultThread implements EliteThreadInvoke {
    private static final Log log = LogFactory.getLog(autoUnicomResultThread.class);

    public int doCallBack(EliteBean eliteBean, String content) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        String logPix = "###当前获取短信结果线程-content:" + content;
        log.debug(logPix);
        try {
            // 查询当前线程对应的信息
            String selectThreadInfo = "Select Top 1 Thread_Guid From Elitethread Where Content = '" + content + "' And Type = 'UnSMSResult'"

            // 标记当前线程执行中
            List<Map<String, Object>> selectThreadList = jt.queryForList(selectThreadInfo);
            jt.update("update Elitethread set Status=1, createdate = Getdate() Where 1=1 and Thread_Guid= '" + selectThreadList.get(0).get("Thread_Guid") + "'");

            // 根据当前线程信息执行任务
            String loginName = content;
            log.debug(logPix + " 获取对应账号:" + loginName);

            int whileNum = 0;
            boolean isContinue = true;

            while (isContinue) {
                whileNum++;
                log.debug(logPix + " 当前获取结果轮次:" + whileNum);
                // 解析短信结果推送
                JSONObject sendResultJson = KHSWUtil.resultSWSms(eliteBean, loginName);

                try {

                    // 解析返回信息
                    JSONArray reportList = sendResultJson.has("data") ? sendResultJson.getJSONArray("data") : [];

                    // 短信结果累加器
                    int loopLogNum = 0;
                    int loopNum = 0;
                    int loopUCISNum = 0;

                    // 普通短信入参
                    List<Object[]> paramSMSLog = new ArrayList<>();

                    // 普通短信入参
                    List<Object[]> paramDocOutSMS = new ArrayList<>();

                    // 批量短信入参
                    List<Object[]> paramDocOutUCIS = new ArrayList<>();
                    List<Object[]> paramSMSResultUCIS = new ArrayList<>();

                    // 循环解析结果处理到DB
                    int listSize = reportList.size();
                    log.debug(logPix + " 获取结果数量:" + listSize);

                    if (listSize <= 0 || whileNum >= 10) {
                        log.debug(logPix + " 本次线程不满足继续执行...");
                        isContinue = false;
                    }

                    for (int i = 0; i < listSize; i++) {

                        String callMdn = reportList.getJSONObject(i).getString("callMdn");
                        String mobile = reportList.getJSONObject(i).getString("mobile");
                        String msgId = reportList.getJSONObject(i).getString("msgId");
                        String reportTime = reportList.getJSONObject(i).getString("reportTime");
                        String status = reportList.getJSONObject(i).getString("status");
                        String statusDes = reportList.getJSONObject(i).getString("statusDes");
                        String userMsgId = reportList.getJSONObject(i).getString("userMsgId");
                        log.debug(logPix + " -userMsgId:" + userMsgId + " mobile:" + mobile + " msgId:" + msgId + " status:" + status + " statusDes:" + statusDes + " reportTime:" + reportTime);

                        String[] paramLogArr = new String[7];
                        paramLogArr[0] = callMdn;
                        paramLogArr[1] = mobile;
                        paramLogArr[2] = msgId;
                        paramLogArr[3] = reportTime;
                        paramLogArr[4] = status;
                        paramLogArr[5] = statusDes;
                        paramLogArr[6] = userMsgId;
                        paramSMSLog.add(paramLogArr);

                        loopLogNum++;

                        // 如果userMsgId字段是BSMS_开头则更新UCIS相关短信表
                        if (userMsgId.startsWith("BSMS_")) {
                            String[] paramArr = new String[5];
                            paramArr[0] = status;
                            paramArr[1] = statusDes;
                            paramArr[2] = status;
                            paramArr[3] = msgId;
                            paramArr[4] = userMsgId;
                            paramDocOutUCIS.add(paramArr);

                            String[] paramUcis = new String[2];
                            paramUcis[0] = msgId;
                            paramUcis[1] = userMsgId;
                            paramSMSResultUCIS.add(paramUcis);

                            loopUCISNum++;

                        } else {
                            String[] paramArr = new String[5];
                            paramArr[0] = status;
                            paramArr[1] = reportTime;
                            paramArr[2] = statusDes;
                            paramArr[3] = msgId;
                            paramArr[4] = userMsgId;
                            paramDocOutSMS.add(paramArr);

                            loopNum++;
                        }

                        // 短信Log-如果当前批次已经到100提交一次DB
                        if (loopLogNum >= 200) {

                            log.debug(logPix + " 短信Log-如果当前批次已经到" + loopNum + "提交一次DB");
                            doLogToDB(jt, paramSMSLog, logPix);
                            log.debug(logPix + " 短信Log-如果当前批次已经到" + loopNum + "提交一次DB End");
                            paramSMSLog.clear();

                            loopLogNum = 0;
                        }

                        // 普通短信-如果当前批次已经到100提交一次DB
                        if (loopNum >= 200) {

                            log.debug(logPix + " 普通短信-如果当前批次已经到" + loopNum + "提交一次DB");
                            doResultToDB(jt, paramDocOutSMS, logPix);
                            log.debug(logPix + " 普通短信-如果当前批次已经到" + loopNum + "提交一次DB End");
                            paramDocOutSMS.clear();

                            loopNum = 0;
                        }
                        // 批量短信-如果当前批次已经到100提交一次DB
                        if (loopUCISNum >= 200) {

                            log.debug(logPix + " 批量短信-如果当前批次已经到" + loopUCISNum + "提交一次DB");
                            doResultUCISToDB(jt, paramDocOutUCIS, paramSMSResultUCIS, logPix);
                            log.debug(logPix + " 批量短信-如果当前批次已经到" + loopUCISNum + "提交一次DB End");
                            paramDocOutSMS.clear();

                            loopUCISNum = 0;
                        }

                    }

                    // 短信Log-最后批次未达到200提交一次DB
                    if (loopLogNum > 0) {
                        log.debug(logPix + " 短信Log-最后批次达到" + loopNum + "提交一次DB");
                        doLogToDB(jt, paramSMSLog, logPix);
                        log.debug(logPix + " 短信Log-最后批次达到" + loopNum + "提交一次DB End");
                    }

                    // 普通短信-最后批次未达到200提交一次DB
                    if (loopNum > 0) {
                        log.debug(logPix + " 普通短信-最后批次达到" + loopNum + "提交一次DB");
                        doResultToDB(jt, paramDocOutSMS, logPix);
                        log.debug(logPix + " 普通短信-最后批次达到" + loopNum + "提交一次DB End");
                    }
                    // 批量短信-最后批次未达到200提交一次DB
                    if (loopUCISNum > 0) {
                        log.debug(logPix + " 批量短信-最后批次达到" + loopNum + "提交一次DB");
                        doResultUCISToDB(jt, paramDocOutUCIS, paramSMSResultUCIS, logPix);
                        log.debug(logPix + " 批量短信-最后批次达到" + loopNum + "提交一次DB End");
                    }

                } catch (Exception e) {
                    log.error(logPix + " 短信结果数据处理异常" + e.getMessage());
                }

            }

        } catch (Exception e) {
            log.error(logPix + " 短信结果接口处理异常：", e);
        }
        return 1;
    }

    // 短信Log操作数据库
    public static void doLogToDB(JdbcTemplate jt, List<Object[]> paramList, String logPix) {
        String batchInsert = '''Insert Into Sw_Smsresult_Log
                                  (Rec_Guid, Callmdn, Mobile, Msgid, Reporttime, Status, Statusdes, Usermsgid, Sync_Time)
                                Values
                                  (Newid(), ?, ?, ?, ?, ?, ?, ?, Getdate())''';
        int[] updateRes = jt.batchUpdate(batchInsert, paramList);

        log.debug(logPix + " 数据库提交操作结果:" + updateRes);

    }

    // 普通短信结果操作数据库
    public static void doResultToDB(JdbcTemplate jt, List<Object[]> paramList, String logPix) {
        String batchInsert = '''Update Documentout
                                   Set Result         = ?,
                                       Finishdatetime = ?,
                                       Modifiedby     = 'SELITE',
                                       Modifieddate   = Getdate(),
                                       Resulttrytime  = Getdate(),
                                       Comments       = ?
                                 Where ResultCode = ? and userMsgId = ?''';
        int[] updateRes = jt.batchUpdate(batchInsert, paramList);

        log.debug(logPix + " 数据库提交操作结果:" + updateRes);

    }

    // 催缴短信结果操作数据库
    public static void doResultUCISToDB(JdbcTemplate jt, List<Object[]> paramDocumentout, List<Object[]> paramSendsmsresult, String logPix) {
        String batchInsert = '''Update Documentout_Ucis
                                   Set Result_Code = ?,
                                       Result_Msg  = ?,
                                       Result_Time = Getdate(),
                                       Smsstatus   = ?
                                 Where Resultcode = ?
                                   And userMsgId = ?''';
        int[] updateRes = jt.batchUpdate(batchInsert, paramDocumentout);
        log.debug(logPix + " 数据库提交操作结果(1/2):" + updateRes);

        String batchResult = '''Insert Into Ucis_Proc_Sendsmsresult
                                  (Rec_Guid, Send_Guid, Send_Time, Sms_Guid, Sync_Time, Smsstatus)
                                  Select Newid(), R1.Documentout_Guid, R1.Send_Time, R1.Sms_Guid, Getdate(), R1.Smsstatus
                                    From Documentout_Ucis R1
                                    Left Join Ucis_Proc_Sendsmsresult R2
                                      On R1.Documentout_Guid = R2.Send_Guid
                                   Where Resultcode = ?
                                     And Usermsgid = ?
                                     And R2.Send_Guid Is Null''';
        updateRes = jt.batchUpdate(batchResult, paramSendsmsresult);
        log.debug(logPix + " 数据库提交操作结果(2/2):" + updateRes);

    }
}
